package pers.qianyu.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import pers.qianyu.interceptor.RateLimitInterceptor;
import pers.qianyu.module.security.interceptor.SecurityInterceptor;

import javax.annotation.Resource;

/**
 * @author mizzle rain
 * @date 2020-10-14 10:10
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Value("${path.uploads}")
    private String uploadsFilePath;
    @Resource
    private RateLimitInterceptor rateLimitInterceptor;
    @Autowired
    private SecurityInterceptor securityInterceptor;

    /**
     * 向 Web 添加拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(rateLimitInterceptor)
                .addPathPatterns("/**");
        registry.addInterceptor(securityInterceptor)
                .addPathPatterns("/**");
    }

    /**
     * 静态资源配置
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 上传的文件被保存的位置
        registry.addResourceHandler("/uploads/**")
                .addResourceLocations("file:./_uploads/");
        // Knife4j 资源
        registry.addResourceHandler("doc.html", "service-worker.js")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        // 上传的文件被保存的位置
        registry.addResourceHandler("/uploads/**")
                .addResourceLocations("file:" + uploadsFilePath + "/");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //添加映射路径
        registry.addMapping("/**")
                //放行哪些原始域
                .allowedOrigins("*")
                //是否发送Cookie信息
                .allowCredentials(true)
                //放行哪些原始域(请求方式)
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD")
                //放行哪些原始域(头部信息)
                .allowedHeaders("*")
                .exposedHeaders("uuid", "sign");
    }
}
